package com.nakamachizu.controller;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.StringUtil;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.nakamachizu.constant.AppConstant;
import com.nakamachizu.constant.SessionKeyConstant;
import com.nakamachizu.model.MapData;
import com.nakamachizu.model.session.MapDataSession;
import com.nakamachizu.service.MapDataService;
import com.nakamachizu.util.ForwardUtil;

public class ConfigController extends Controller {

    @Override
    public Navigation run() {
        
        String forwardJsp = "config.jsp";
        String keyStr = requestScope("key");
        String viewPassword = requestScope("viewPassword");
        String expire = requestScope("expire");
        String cmd = requestScope("cmd");
        String title = requestScope("title");
        String line = requestScope("line");
        String from = requestScope("from");
        
        if(StringUtil.isEmpty(keyStr)){
            MapDataSession ses = sessionScope(SessionKeyConstant.MAP_DATA_SESSION_KEY());
            if(ses != null){
                keyStr = ses.getMapKey();
            }else{
                return redirect("/view");
            }
        }
        
        UserService userService = UserServiceFactory.getUserService();        
        User user = userService.getCurrentUser();
        String logoutUrl = userService.createLogoutURL("/");

        MapDataService mds = new MapDataService();
        MapData map = mds.getMapDataAccessKey(keyStr);
        
        if(map == null || user == null || !user.getEmail().equals(map.getAdminMailAddress())){
            return redirect("/");
        }
        
        requestScope("userMailAddress", user.getEmail());
        requestScope("welcomeMailAddress", AppConstant.WELCOME_MAIL_ADDRESS());
        
        if(StringUtil.isEmpty(map.getLineType())){
            map.setLineType(AppConstant.LINE_TYPE_LINE());
        }
    
        if(!StringUtil.isEmpty(cmd) && validate()){
            
            boolean modify = false;
            
            if(viewPassword == null){
                viewPassword = "";
            }
            if(!viewPassword.equals(map.getViewPassword())){
                map.setViewPassword(viewPassword);
                modify = true;
            }
            if(!StringUtil.isEmpty(expire)){
                map.setExpire(mds.getExpire(Integer.parseInt(expire)));
                modify = true;
            }
            if(title == null){
                title = "";
            }
            if(!title.equals(map.getTitle())){
                map.setTitle(title);
                modify = true;
            }
            
            if(!map.getLineType().equals(line)){
                map.setLineType(line);
                modify = true;
            }
            
            if(!map.getFromMailAddress().equals(from)){
                if(AppConstant.FROM_MAIL_ADDRESS_SYSTEM().equals(from)){
                    map.setFromMailAddress(AppConstant.FROM_MAIL_ADDRESS_SYSTEM());
                }else{
                    map.setFromMailAddress(AppConstant.FROM_MAIL_ADDRESS_USER());
                }
                modify = true;
            }
            
            map.setAccessLevel(AppConstant.ACCESSLEVEL_ALL());
            
            if(modify){
                Datastore.put(map);
                forwardJsp = "config_end.jsp";
            }
        }
        
        requestScope("expireDate", map.getExpire());
        if(StringUtil.isEmpty(cmd)){
            requestScope("viewPassword", map.getViewPassword());
            requestScope("title", map.getTitle());
            requestScope("line", map.getLineType());
            requestScope("from", map.getFromMailAddress());
        }

        
        return forward(ForwardUtil.forwardJsp(forwardJsp));
    }
    
    protected boolean validate() {
        boolean result = false;
        Validators v = new Validators(request);
        v.add("viewPassword", v.minlength(3));
        v.add("viewPassword", v.maxlength(16));
        v.add("expire", v.longRange(1, 10));
        v.add("title", v.maxlength(16));
        v.add("line", v.required());
        v.add("line", v.longRange(1, 3));
        v.add("from", v.required());
        v.add("viewPassword", v.regexp("^[a-zA-Z0-9]+$", "閲覧パスワードは半角英数字で入力してください。"));
        
        result = v.validate();
        
        return result;
    }
}
